<!--三包预警参数管理 厂端-->
<template>
  <div>
    <TopFilter ref="topfilter" :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :onSyncTableData="tableChangeFun"
      :isExportExcel="false"
      exportFileName="三包预警参数管理.xlsx"
      :onCalcExportData="handleExportFun"
      :onCellChange="onCellChange"
      :cellstyles="cellstyles"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>

        <!--        <multiuse-button type="primary" :click="exportHandle.bind(this)">导出</multiuse-button>-->
      </template>
    </FilterTable>
    <BaseDialog
      :visible.sync="visibleAdd"
      :title="'三包参数设定新增'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>

    <Drawer :visible.sync="visibleDetail" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :formData="formData" @close="closeHandler" :handleType="handleType" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import detail from './detail';
import { isEmpty } from '@/utils/utils';
import { listParaRecord, updatePara, exportParaRecord } from '@/api/repair/threePacksOfManager/warningParameterManagementCDuan';
import AddForm from './addForm.vue';
export default {
  name: 'addItem',
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      visible: false,
      visibleAdd: false,
      visibleDetail: false,
      fetchApi: listParaRecord,
      dialogTitle: '',
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      cellstyles: []
    };
  },
  components: {
    detail,AddForm
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
  },
  methods: {
    async exportHandle() {
      const [err, params] = await this.$refs.topfilter.GET_FORM_DATA();

      await this.downHandleFile(exportParaRecord, params, '三包预警参数管理');
    },

    async initSelect() {
      // let res = await getAllUser();
      // // 去重
      // let dataList = arrayObjDeWeight(res.data, 'userId');
      //
      // this.columns.find(item => item.dataIndex === 'createdBy').dictItems = dataList.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId
      // }));
      //
      // this.columns.find(item => item.dataIndex === 'updatedBy').dictItems = dataList.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId
      // }));

      // this.getAllUsers(this.columns, ['createdBy', 'updatedBy'], 'table');
    },

    tableChangeFun(dataList) {
      dataList.forEach((item, index) => {
        this.cellstyles.push({ row: item, dataIndex: 'red', styles: { backgroundColor: 'red' } });
        this.cellstyles.push({ row: item, dataIndex: 'orange', styles: { backgroundColor: 'orange' } });
        this.cellstyles.push({ row: item, dataIndex: 'yellow', styles: { backgroundColor: 'yellow' } });
      });

      console.log('tableChangeFun---', dataList);
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    /*配置数量发生改变的时候执行*/
    onCellChange(e, obj) {
      // this.BaseTable.DO_REFRESH(false)
    },
    // 导出处理函数
    handleExportFun(row) {
      row.status = row.status == '10011001' ? '有效' : '无效';
      // row.type = this.createDictText(row.type, 1023);
    },

    async saveHandle(row, status) {
      let red = isEmpty(row['red']) ? '0' : `${row['red']}`;
      let yellow = isEmpty(row['yellow']) ? '0' : `${row['yellow']}`;
      let orange = isEmpty(row['orange']) ? '0' : `${row['orange']}`;

      if (status == '0') {
        let regExp = /(^[0-9]\d*$)/;

        if (!regExp.test(red)) {
          this.$notify.warning({ title: '提示信息', message: '红色预警数值只能是整数' });
          return;
        }
        if (!regExp.test(orange)) {
          this.$notify.warning({ title: '提示信息', message: '橙色预警数值只能是整数' });
          return;
        }
        if (!regExp.test(yellow)) {
          this.$notify.warning({ title: '提示信息', message: '黄色预警数值只能是整数' });
          return;
        }
        if (
          parseFloat(red) < parseFloat(yellow) ||
          parseFloat(red) == parseFloat(yellow) ||
          parseFloat(red) < parseFloat(orange) ||
          parseFloat(red) == parseFloat(orange) ||
          parseFloat(orange) < parseFloat(yellow) ||
          parseFloat(orange) == parseFloat(yellow)
        ) {
          this.$notify.warning({ title: '提示信息', message: '预警级别的优先级为红>橙>黄' });
          return;
        }
      }
      let res = await updatePara({
        paraId: row['paraId'],
        red: red,
        yellow: yellow,
        orange: orange,
        status: status,
        isDeleted:0
      });
      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = { ...this.fetchParams };

        this.$notify.success({ title: '提示信息', message: '操作成功' });
      }
    },
    async delHandle(row) {

      let res = await updatePara({
        paraId: row['paraId'],
        status: 1,
        isDeleted:1
      });
      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = { ...this.fetchParams };

        this.$notify.success({ title: '提示信息', message: '操作成功' });
      }
    },
    detailHandle(row) {
      this.formData = row;
      this.handleType = 'show';
      this.showHandler();
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 190,
          render: props => {
            let status = props.row.status == '10011001' ? '10011002' : '10011001';
            let statusName = props.row.status == '10011001' ? '无效' : '有效';

            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  详情
                </el-button>
                <el-divider direction="vertical" />
                <multiuse-button type="text" size="mini" click={() => this.saveHandle(props.row, status)}>
                  {statusName}
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button type="text" size="mini" disabled={statusName == '有效' ? true : false} click={() => this.saveHandle(props.row, '0')}>
                  保存
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button type="text" size="mini" click={() => this.delHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          sorter: true,
          filterItems: this.createDictList(1001),
          render: props => {
            let status = props.row.status == '10011001' ? '有效' : '无效';
            return <span>{status}</span>;
          }
        },
        {
          title: '规则编号',
          dataIndex: 'threeNo',
          sorter: true
        },
        {
          title: '规则名称',
          dataIndex: 'threeName',
          sorter: true
        },
        // {
        //   title: '规则类型',
        //   dataIndex: 'type',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList(1023),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.type, 1023)}</span>;
        //   }
        // },
        // {
        //   title: '预警单位',
        //   dataIndex: 'unit',
        //   sorter: true
        // },
        {
          title: '红色预警',
          dataIndex: 'red',
          sorter: true,
          editType: 'number',
          defaultEditable: false,
          editable: true,
          className: 'red'
          //
          // render: props =>
          // {
          //   return <input style="color: red">{props.row.red}</input>;
          // }
        },
        {
          title: '橙色预警',
          dataIndex: 'orange',
          sorter: true,
          defaultEditable: false,
          editType: 'number',
          editable: true
          // render: props =>
          // {
          //   return <input style="color: orange">{props.row.orange}</input>;
          // }
        },
        {
          title: '黄色预警',
          dataIndex: 'yellow',
          width: 150,
          sorter: true,
          defaultEditable: false,
          editType: 'number',
          editable: true
          // render: props =>
          // {
          //   return <input style="color: yellow">{props.row.yellow}</input>;
          // }
        },
        // {
        //   title: '法定时限(月)',
        //   dataIndex: 'months',
        //   showOverflowTooltip: true,
        //   sorter: true
        // },
        // {
        //   title: '法定里程(KM)',
        //   dataIndex: 'mileage',
        //   showOverflowTooltip: true,
        //   sorter: true
        // },
        // {
        //   title: '创建人',
        //   dataIndex: 'createdBy',
        //   showOverflowTooltip: true,
        //   sorter: true,
        //   dictItems: []
        // },
        // {
        //   title: '创建时间',
        //   dataIndex: 'createdAt',
        //   width: 150,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range'
        // },
        // {
        //   title: '修改人',
        //   dataIndex: 'updatedBy',
        //   showOverflowTooltip: true,
        //   sorter: true,
        //   dictItems: []
        // },
        // {
        //   title: '修改时间',
        //   dataIndex: 'updatedAt',
        //   width: 150,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range'
        // }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '规则编号',
          fieldName: 'threeNo',
          placeholder: '规则编号...'
        },
        {
          type: 'INPUT',
          label: '规则名称',
          fieldName: 'threeName',
          placeholder: '规则名称...'
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'status',
          placeholder: '状态',
          itemList: this.createDictList(1001)
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    changeHandle(val) {
      // val.bDate=moment(val['bDate']).format('YYYY-MM-DD')
      // val.eDate=moment(val['eDate']).format('YYYY-MM-DD')
      this.fetchParams = Object.assign({}, val);

      console.log(this.fetchParams);
    },
    showHandler() {
      // this.dialogTitle = `${this.conf[this.handleType]}三包预警参数管理`;
      this.dialogTitle = '三包预警参数设定详情';

      this.visibleDetail = true;
    },

    closeHandler(type) {
      this.visible = false;
      this.visibleDetail = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped>
.red {
  color: red !important;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}
</style>
